﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ChartEdit
{
    public class EventsSection : List<EventsSectionEntry>
    {
        public const string SectionName = "Events";
        public EventsSectionEntry this[string s]
        {
            get
            {
                foreach (EventsSectionEntry e in this)
                {
                    if (e.TextValue == s)
                        return e;
                }
                return null;
            }
        }

    }

    public enum EventType
    {
        Text,
        Effect
    }
    public class EventsSectionEntry
    {
        static readonly Regex EventTextRegex = new Regex( "(?<offset>\\d+)\\s*\\=\\s*E\\s*\\\"(?<value>.*)\\\"", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline );
        static readonly Regex EventEffectRegex = new Regex( @"\s*(?<offset>\d+)\s*\=\s*H\s*(?<type>\d+)\s*(?<len>\d+)", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline );

        public int Offset { get; set; }

        public EventType Type { get; set; }

        public string TextValue { get; set; }

        public int EffectType { get; set; }
        public int EffectLength { get; set; }

        public static EventsSectionEntry Parse( string entryStr )
        {
            Match match = EventTextRegex.Match( entryStr );

            EventsSectionEntry entry = new EventsSectionEntry();

            if ( !match.Success )
            {
                match = EventEffectRegex.Match( entryStr );

                if ( !match.Success )
                    return null;

                int offset = int.Parse( match.Groups[ "offset" ].Value.Trim() ); // this should always succeed due to \d in regex
                int effectType = int.Parse( match.Groups[ "type" ].Value.Trim() );
                int effectLength = int.Parse( match.Groups[ "len" ].Value.Trim() );

                entry.Type = EventType.Effect;

                entry.Offset = offset;
                entry.EffectLength = effectLength;
                entry.EffectType = effectType;

                return entry;
            }


            int off = int.Parse( match.Groups[ "offset" ].Value.Trim() ); // this should always succeed due to \d in regex

            string value = match.Groups[ "value" ].Value.Trim();

            entry.Type = EventType.Text;
            entry.Offset = off;
            entry.TextValue = value;

            return entry;
        }
    }
}
